using DBEntitie;
using FrameWork;
using lhservice.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Threading.Tasks;
using lhservice.common;
using Hangfire;
using lhservice.common.websocket;
using System.Reflection;
using System.Configuration;
using log4net.Core;
using System.ServiceProcess;

namespace lhservice.Controllers
{
  /// <summary>
  /// 调试维护
  /// </summary>
  [Authorize]
  [ApiController]
  [Route("api/[controller]")]
  [AllowAnonymous]
  public class DebugController : TimController
  {
    /// <summary>
    /// 有结果集返回的SQL语句
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [HttpPost("[action]")]
    public async Task<IActionResult> done([FromBody] Dictionary<string, string> data)
    {

      if (Request.Headers["cauth"].ToString() != "123") return await PublicTool.ReturnError("您没有调试接口权限");
      string sql = data["sql"];

      if (String.IsNullOrEmpty(sql)) return await PublicTool.ReturnError("没有sql传参");

      var res = new List<Dictionary<string, dynamic>>();
      using (var db = new SyBaseEntities())
      {
        if (sql.StartsWith("select"))
        {
          var table = db.QueryTable(sql);
          res = table.ToList();
        }
        else
        {
          var n = db.Execute(sql);
          res.Add(new Dictionary<string, dynamic> { ["affected Nums"] = n });
        }
      }
      return await PublicTool.ReturnSuccess(res);
    }


    [HttpPost("[action]")]
    public async Task<IActionResult> UpdateDataSource([FromBody] Dictionary<string, string> data)
    {

      if (Request.Headers["cauth"].ToString() != "123") return await PublicTool.ReturnError("您没有调试接口权限");

      string reportname = data["reportname"];
      string sql = data["sql"];
      string fname = Path.Combine("report", reportname + ".sql");

      if (!System.IO.File.Exists(fname))
      {
        FileStream f = new FileStream(fname, FileMode.Create, FileAccess.ReadWrite);
        f.Close();
      }

      System.IO.File.WriteAllText(fname, sql);
      return await PublicTool.ReturnSuccess("ok");
    }

    [HttpGet("[action]")]
    public async Task<IActionResult> GetReportList()
    {
      string[] files = Directory.GetFiles("report", "*.sql");
      var dataSourceList = new List<Dictionary<string,string>>();
      foreach (var path in files)
      {
        string _name = Path.GetFileName(path).Split(".")[0];
        dataSourceList.Add(new Dictionary<string, string> { ["value"]=_name,["label"]=_name});
      }
      return await PublicTool.ReturnSuccess(dataSourceList);
    }

    [HttpGet("[action]")]
    public async Task<IActionResult> GetReportSql(string reportname)
    {
      string fname = Path.Combine("report", reportname + ".sql");
      var content = System.IO.File.ReadAllText(fname);
      return await PublicTool.ReturnSuccess(content);
    }
  }
}
